﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace lopet.data
{
    /// <summary>
    /// Not used by anyone for now
    /// </summary>
    private class Line
    {
        public Point A { get; set; }
        public Point B { get; set; }

        public Line(Point A,Point B)
        {
            this.A = A;
            this.B = B;            
        }
        
        public double Length 
        {
            get 
            {
                return Math.Sqrt((B.Y - A.Y).Squared() + (B.X - A.X).Squared() + (B.Z - A.Z).Squared());
            }
        }

        public bool cellIntersect(Cell cell) // 2d
        {
            var line = this;
            double dx = line.B.X - line.A.X;
            double dy = line.B.Y - line.A.Y;
            double a = dx.Squared() + dy.Squared();
            double b = 2 * (dx * (line.A.X - cell.Center.X) + dy * (line.A.Y - cell.Center.Y));
            double c = cell.Center.X.Squared() + cell.Center.Y.Squared();
            c += line.A.X.Squared() + line.A.Y.Squared();
            c -= 2 * (cell.Center.X * line.A.X + cell.Center.Y * line.A.Y);
            c -= cell.Radius * cell.Radius;
            double bb4ac = b * b - 4 * a * c;

            if (bb4ac < 0)
            {  // Not intersecting
                return false;
            }
            else
            {
                double mu = (-b + Math.Sqrt(b * b - 4 * a * c)) / (2 * a);
                double ix1 = line.A.X + mu * (dx);
                double iy1 = line.A.Y + mu * (dy);
                mu = (-b - Math.Sqrt(b * b - 4 * a * c)) / (2 * a);
                double ix2 = line.A.X + mu * (dx);
                double iy2 = line.A.Y + mu * (dy);

                double testX;
                double testY;
                var lineA = new Line(line.A, cell.Center);
                var lineB = new Line(line.B, cell.Center);
                Line lineTest;
                if (lineA.Length < lineB.Length)
                {
                    testX = line.B.X;
                    testY = line.B.Y;
                    lineTest = new Line(line.B, new Point { X = ix1, Y = iy1 });
                }
                else
                {
                    testX = line.A.X;
                    testY = line.A.Y;
                    lineTest = new Line(line.A, new Point { X = ix2, Y = iy2 });
                }
                if (lineTest.Length < line.Length || lineTest.Length < line.Length)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
    }
}
